package com.coolwen.controller;

import com.alibaba.fastjson.JSON;
import com.coolwen.entity.User;
import com.coolwen.service.UserService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by user on 2016/6/29.
 */
@Controller
@SessionAttributes("loginUser")
@RequestMapping("/login")
public class LoginController {
    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model) {
//        LoginUser loginUser = new LoginUser();
//        User user = new User();
        model.addAttribute(new User());
        return "login/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@Validated User user, BindingResult br, Model model, HttpServletRequest request) {
        if (br.hasErrors()) {
            //如果有错误直接跳转到login视图
            return "login/login";
        }

        String loginName = user.getUsername();
        String loginPassword = user.getPassword();


        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginName, loginPassword);

        //     logger.info("查找用户名Controller:" + loginName + "查找用密码Controller:" + loginPassword);
        String msg = null;

        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            msg = "用户名/密码错误";
        } catch (IncorrectCredentialsException e) {
            msg = "用户名/密码错误";
        } catch (ExcessiveAttemptsException e) {
            // TODO: handle exception
            msg = "登录失败多次，账户锁定1小时!";
        } catch (AuthenticationException e) {
            msg = e.getMessage();
            //           logger.info("登录信息MSG:" + msg);
        }
        if (msg != null) {
            model.addAttribute("msg", msg);
            //          logger.info("登录信息MSG:" + msg);
            return "/login/login";
        } else {
            user.setLoginData(new Date());

            User loginUser = (User) subject.getPrincipals().getPrimaryPrincipal();
            model.addAttribute("loginUser", loginUser);
            //           logger.info("登录时间:" + user.getLoginData());
            //           logger.info("登录:" + JSON.toJSON(user));
//            userService.update(user);
            return "redirect:/admin/user/show";
        }


    }
}
